function showEditForm(menuId) {
    document.getElementById('edit-form-' + menuId).style.display = 'block';
}

function deleteMenu(menuId) {
    if (confirm('确定要删除此菜单吗？')) {
        fetch('/delete_menu/' + menuId, {
            method: 'POST',
        })
        .then(response => {
            if (response.ok) {
                window.location.href = '/';  // 重定向到主页
            } else {
                alert('删除失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败');
        });
    }
}

function orderMenu(menuId) {
    console.log("Ordering menu with ID:", menuId);
    fetch(`/order_menu/${menuId}`, {
        method: 'POST',
    })
    .then(response => {
        console.log("Order response status:", response.status);
        return response.json();
    })
    .then(data => {
        console.log("Order response data:", data);
        if (data.status === 'success') {
            // 显示一个非阻塞的提示框
            const successMessage = document.createElement('div');
            successMessage.textContent = '点餐成功！';
            successMessage.style.position = 'fixed';
            successMessage.style.bottom = '20px';
            successMessage.style.right = '20px';
            successMessage.style.backgroundColor = '#4CAF50';
            successMessage.style.color = 'white';
            successMessage.style.padding = '10px 20px';
            successMessage.style.borderRadius = '5px';
            successMessage.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
            document.body.appendChild(successMessage);

            // 自动隐藏提示框
            setTimeout(() => {
                document.body.removeChild(successMessage);
            }, 1000);

         
        } else {
            alert('点餐失败1，请重试。');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (error.message && error.message.includes('point of failure 2')) {
            alert('点餐失败2，请重试。' + (error.message || ''));
        } else {
            alert('点餐失败，请重试。' + (error.message || ''));
        }
    });
}
window.onload = function() {
    updateOrderedMenus();
};
function updateOrderedMenus() {
    fetch('/get_ordered_menus', {
        method: 'GET',
    })
   .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
   .then(data => {
        console.log("Data received from server:", data);
        if (data.orders) {
            const orderedMenusContainer = document.getElementById('ordered-menus');
            if (orderedMenusContainer) {
                orderedMenusContainer.innerHTML = ''; // 清空已点餐项列表
                data.orders.forEach(order => {
                    const orderedMenuItem = document.createElement('div');
                    orderedMenuItem.className = 'ordered-menu-item';
                    orderedMenuItem.setAttribute('data-order-id', order.order_id);
                    orderedMenuItem.innerHTML = `
                        <h3>${order.name}</h3>
                        <p>价格: ${order.price}</p>
                        <button onclick="deleteOrderedMenu(${order.order_id})">删除</button>
                    `;
                    orderedMenusContainer.appendChild(orderedMenuItem);
                   
                    });
            } else {
                // 仅在当前页面是已点餐页面时才报错
                if (window.location.pathname === '/ordered_menus') {
                    console.error('Element with ID "ordered-menus" not found');
                    alert('更新已点餐项失败，请重试。');
                }
            }
        } else {
            // 仅在当前页面是已点餐页面时才报错
            if (window.location.pathname === '/ordered_menus') {
                console.error('No orders data received');
                alert('更新已点餐项失败，请重试。');
            }
        }
        // 事件委托处理删除按钮点击事件
        document.addEventListener('click', function(event) {
            if (event.target.classList.contains('delete-ordered-menu-button')) {
                const orderId = event.target.getAttribute('data-order-id');
                deleteOrderedMenu(orderId);
            }
});
    })
   .catch(error => {
        console.error('Error updating ordered menus:', error);
        // 仅在当前页面是已点餐页面时才报错
        if (window.location.pathname === '/ordered_menus') {
            alert('更新已点餐项失败，请重试。' + (error.message || ''));
        }
    });
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function deleteOrderedMenu(orderId) {
    if (confirm('确定要删除此已点餐项吗？')) {
        fetch('/delete_ordered_menu/' + orderId, {
            method: 'POST',
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                showToast('删除成功！');
                // 移除对应的已点餐项元素
                
                const orderedMenuItem = document.querySelector(`.ordered-menu-item[data-order-id="${orderId}"]`);
                if (orderedMenuItem) {
                    orderedMenuItem.remove();
                }
                // 刷新页面
                location.reload();
            } else {
                alert('删除已点餐项失败，请重试。');
            }
        })
        .catch(error => {
            console.error('Error deleting ordered menu:', error);
            alert('删除已点餐项失败，请重试。');
        });
    }
}
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('show');
    }, 100);

    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 500);
    }, 2500);
}